﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using SWE4.Data.EmbeddedSensorCloud.DTO.Request;
using EmbeddedSensorCloud.HTTP;
using Newtonsoft.Json;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class UpdateInvoiceCommand : ICommand
    {
        #region Fields

        IInvoiceDAO _InvoiceDao;
        JsonSerializerSettings _JsonSettings;

        #endregion

        #region Constructor

        public UpdateInvoiceCommand(IInvoiceDAO invoiceDao, JsonSerializerSettings jsonSettings)
        {
            this._InvoiceDao = invoiceDao;
            this._JsonSettings = jsonSettings;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "PUT" &&
                    Regex.IsMatch(param.Url, @"^/api/invoice/[0-9]+$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            uint id;
            string[] urlParts = param.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (urlParts.Length != 3 || !uint.TryParse(urlParts[2], out id) || string.IsNullOrWhiteSpace(param.Body))
            { throw new BadRequestException(); }

            var model = JsonConvert.DeserializeObject<InvoiceRequestModel>(param.Body, this._JsonSettings);
            this._InvoiceDao.Update(model, id);

            return new ResponseEntity(null, HttpStatusCode.NoContent);
        }

        #endregion
    }
}
